import java.awt.*;

public class AlgoVisualizer {

    private static int DELAY = 40;

    private MonteCarloPiData data;
    private int N;
    private AlgoFrame frame;

    public AlgoVisualizer(int sceneWidth, int sceneHeight, int N) {
        if (sceneWidth != sceneHeight) {
            throw new IllegalArgumentException("此 demo 必须运行在一个正方形视图中！");
        }

        // 初始化数据
        Circle circle = new Circle(sceneWidth / 2, sceneHeight / 2, sceneWidth / 2);
        data = new MonteCarloPiData(circle);
        this.N = N;

        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Get PI With Monte Carlo", sceneWidth, sceneHeight);

            // https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
            // Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.
            new Thread(this::run).start();
        });
    }

    // 动画逻辑
    private void run() {
        for (int i = 0; i < N; i ++) {

            if (i % 100 == 0) {
                frame.render(data);
                AlgoVisHelper.pause(DELAY);

                System.out.println(data.estimatePi());
            }

            int x = (int) (Math.random() * frame.getCanvasWidth());
            int y = (int) (Math.random() * frame.getCanvasHeight());

            data.addPoint(new Point(x, y));
        }
    }

    public static void main(String[] args) {
        int sceneWidth = 800;
        int sceneHeight = 800;
        int N = 10000;

        AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth, sceneHeight, N);
    }
}
